#include <cmath>
#include <stdexcept>
#include <vector>

#include "./gaussianFilter1D.h"

using namespace std;

vector<double> generateGaussianKernel(int kernelSize, double sigma) {
  if (kernelSize <= 0) {
    throw invalid_argument("核大小必须为正整数");
  }
  if (kernelSize % 2 == 0) {
    throw invalid_argument("核大小必须为奇数"); // 确保对称性
  }
  if (sigma <= 0) {
    throw invalid_argument("标准差σ必须大于0");
  }

  vector<double> kernel(kernelSize);
  int half = kernelSize / 2;
  double sum = 0.0;

  // 计算高斯核权重
  for (int i = -half; i <= half; ++i) {
    double x = i;
    kernel[half + i] = exp(-(x * x) / (2 * sigma * sigma));
    sum += kernel[half + i];
  }

  // 归一化（确保总和为1）
  for (auto &val : kernel) {
    val /= sum;
  }

  return kernel;
}

vector<double> gaussianFilter1D(const vector<double> &input, int kernelSize,
                                double sigma) {
  auto kernel = generateGaussianKernel(kernelSize, sigma);
  int half = kernelSize / 2;
  int n = input.size();
  vector<double> output(n, 0.0);

  for (int i = 0; i < n; ++i) {
    double sum = 0.0;
    for (int j = -half; j <= half; ++j) {
      int idx = i + j;
      // 边界处理：超出范围的值直接忽略
      if (idx >= 0 && idx < n) {
        sum += input[idx] * kernel[j + half];
      }
    }
    output[i] = sum;
  }

  return output;
}